/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.controller;

import com.db.Conector;
import com.db.SqlManager;
import com.exception.DataException;
import com.javabeans.*;
import com.model.*;
import com.util.UtilDate;
import com.util.UtilTransaccion;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Administrador
 */
public class Transacciones extends HttpServlet {

    HttpServletRequest request;
    HttpServletResponse response;
    HttpSession session;
    String msg = "";
    
    private String PAGE = "";
    private static final String ERROR_PAGE = "WEB-INF/error.jsp";
    private static final String ERROR_AJAX = "WEB-INF/errorAjax.jsp";
    boolean isForward = true; // inicializamos con forward....
    Usuario s_Usuario = null;
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        this.request = request;
        this.response = response;
        session = request.getSession();
        int accion = Integer.parseInt(request.getParameter("accion"));
        if(session.getAttribute("s_Usuario") != null){
            s_Usuario = (Usuario)session.getAttribute("s_Usuario");
            try{
                switch(accion){
                    case 1 : indexMatricular(); break;                              // accion = 1 = condiciones para la venta de matricula
                    case 2 : ventaDeMatricula(accion); break;                             // accion = 2 = inicio de matriculacion con el select
                    case 3 : buscarEstudianteXfacultadAjax(accion); break;         // accion = 3 = buscamos al estudiante de una facultad
                    case 4 : insertMatriculaXfacultad(); break;                     // accion = 4 = insertamos matricula en la bd
                    case 5 : buscarEstudianteXfacultadAjax(accion); break;            // accion = 5 = buscamos al estudiante en toda la entidad
                    case 6 : ventaDeMatricula(accion); break;
                    default : System.out.println(" accion = "+accion+" no existe en Transacciones.java"); throw new DataException("accion = "+accion+" no existe en Transaccion.java");
                }
            }catch(DataException e){
                throw new ServletException(e);
            }
        }else
            PAGE = "web/index.jsp?msg=Indentifiquese. La Session no existe!";
        if(PAGE.length() > 0){
            if(isForward){
                RequestDispatcher dispatch = request.getRequestDispatcher(PAGE);
                dispatch.forward(request,response);
            }else{
                response.sendRedirect(PAGE);
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void indexMatricular() throws DataException{// accion <-- 1 inicio de venta de matricula
        Connection c = null;
        
        try{
            c = Conector.getConexion();
            FacultadManager fManager = ManagerFactory.getFacultadManagerInstance(c);
            GestionManager gmanager = ManagerFactory.getGestionManagerInstance(c);
            
            Facultad facultad = fManager.getFacultadAdmin(s_Usuario.getIdUsuario());
            // optener de valores de la entidad PARAMETRO para saber si la venta es facultativo o general
            ParametroManager pManager = ManagerFactory.getParametroManagerInstance(c);            
            if(pManager.getParametro().isVentaMatriculaXfacultad()){// si es true es por facultad la venta                
                request.setAttribute("isNew", true);
                request.setAttribute( "gestiones", gmanager.getGestVigentesYfuturosPorFacult(facultad.getIdFacultad()) );
            }else{// false es cuando solo hay una caja en toda la entidad
                // tengo q enviar lista de todas las facultades donde se haran venta de matricula
                request.setAttribute("isNew", false);
                request.setAttribute("gestiones", gmanager.getGestVigentesYfuturos());
            }
            
            request.setAttribute("facultad", facultad );// idUsuario
            PAGE = "WEB-INF/ADMINISTRATIVO/TRANSACCIONES/matriculacion/index.jsp";
        }catch(DataException e){
            System.out.println(UtilDate.getDateTime()+" Transacciones -> indexMatricular() e: "+e.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Transacciones -> indexMatricular() DataException "+e.getMessage());
            PAGE = ERROR_PAGE;
        }catch(Exception ex){
            System.out.println(UtilDate.getDateTime()+" Transacciones -> indexMatricular() ex: "+ex.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Transacciones -> indexMatricular() Exception ex: "+ex.getMessage());
            PAGE = ERROR_PAGE;
        }finally{
            SqlManager.closeConexion(c);
        }
    }

    private void ventaDeMatricula(int accion) throws DataException {// accion <-- 2 inicio de venta de matricula; 6<-- venta gral
        Connection c = null;
        
        boolean isNew = Boolean.parseBoolean(request.getParameter("isNew"));
        String auxIds[] = request.getParameter("gestion").split("_");// idGestion_idFacultad
        int idGestion = Integer.parseInt( auxIds[0] );
        int idFacultad = Integer.parseInt( auxIds[1] );
        String nombreGestion = request.getParameter("gestionElegido");
        
        String fechaNow = UtilDate.getDateTime();
        try{
            
            c = Conector.getConexion();
            // optener de valores de la entidad PARAMETRO para saber si la venta es facultativo o general
            VentaMatriculaManager vmManager = ManagerFactory.getVentaMatriculaManagerInstance(c);
            FacultadManager fManager = ManagerFactory.getFacultadManagerInstance(c);
            
            Facultad facultad = fManager.getFacultadAdmin(s_Usuario.getIdUsuario());
            if(isNew){// si es true es por facultad la venta
                System.out.println("-------AAA------- : ");
                request.setAttribute("isNew", isNew);
                //request.setAttribute("ventaMatriculaXfacult", vmManager.getVentaMatriculaXfacultad( s_Usuario.getIdUsuario(), UtilDate.getDateTime() ) );
            }else{// false es cuando solo hay una caja en toda la entidad
                // no hay restriccion
                System.out.println("-------BBB------- : ");
                request.setAttribute("isNew", isNew);
            }            
            request.setAttribute("gestionElegido", nombreGestion);
            request.setAttribute("gestion", request.getParameter("gestion") );
            request.setAttribute("facultad", facultad );// facultad
            request.setAttribute("ventaMatriculaXfacult", vmManager.getVentaMatriculaXfacultad( s_Usuario.getIdUsuario(), fechaNow, idGestion, idFacultad, isNew ) );// "2012-07-17 13:32:00"  
            
            PAGE = "WEB-INF/ADMINISTRATIVO/TRANSACCIONES/matriculacion/venta/buscar.jsp";
        }catch(DataException e){
            System.out.println(UtilDate.getDateTime()+" Transacciones -> ventaDeMatricula() e: "+e.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Transacciones -> ventaDeMatricula() DataException "+e.getMessage());
            PAGE = ERROR_PAGE;
        }catch(Exception ex){
            System.out.println(UtilDate.getDateTime()+" Transacciones -> ventaDeMatricula() ex: "+ex.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Transacciones -> ventaDeMatricula() Exception ex: "+ex.getMessage());
            PAGE = ERROR_PAGE;
        }finally{
            SqlManager.closeConexion(c);
        }
    }
    private void buscarEstudianteXfacultadAjax(int accion) throws DataException{// accion <-- 3 buscamos a un estudiante de un facultad; 5 <-- para buscar all
        int codsis = Integer.parseInt(request.getParameter("codsis"));
        int idFacultad = Integer.parseInt(request.getParameter("idFacultad"));
        float costo = Float.parseFloat(request.getParameter("costo"));
        String gestion = request.getParameter("gestion");
        String gral = request.getParameter("gral");//[ isNew|gestion|nombreGestion ] necesario para el dialogo una ves q es satisfactorio
        
        Connection c = null;
        try{
            c = Conector.getConexion();
            CarreraEstudianteManager ceManager = ManagerFactory.getCarreraEstudianteManagerInstance(c);
            List<CarreraEstudiante> c_e = new ArrayList<CarreraEstudiante>();             
            if(accion == 3)
                c_e = ceManager.getCarreraEstudiante( codsis, Integer.parseInt(gestion) ); 
            else
                c_e = ceManager.getCarreraEstudianteAll( codsis, idFacultad, Integer.parseInt(gestion) );
            
            request.setAttribute("c_e", c_e); 
            request.setAttribute("sisCostoGestion", codsis+"_"+costo+"_"+gestion+"_"+idFacultad);// codsis_costo_gestion_idFacultad
            request.setAttribute("gral", gral);
            PAGE = "WEB-INF/ADMINISTRATIVO/TRANSACCIONES/matriculacion/venta/listarDatosAjax.jsp";
        }catch(DataException e){
            System.out.println(UtilDate.getDateTime()+" Transacciones -> buscarEstudianteXfacultadAjax() e: "+e.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Transacciones -> buscarEstudianteXfacultadAjax() DataException "+e.getMessage());
            PAGE = ERROR_AJAX;
        }catch(Exception ex){
            System.out.println(UtilDate.getDateTime()+" Transacciones -> buscarEstudianteXfacultadAjax() ex: "+ex.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Transacciones -> buscarEstudianteXfacultadAjax() Exception ex: "+ex.getMessage());
            PAGE = ERROR_AJAX;
        }finally{
            SqlManager.closeConexion(c);
        }
    }

    private void insertMatriculaXfacultad() throws DataException, IOException{// accion <-- 4 insertamos la matricula
        PAGE = "";
        PrintWriter out = response.getWriter();
        int i = 0;
        
        int codsis = Integer.parseInt(request.getParameter("codsis"));
        float costo = Float.parseFloat(request.getParameter("costo"));
        String carreras[] = request.getParameterValues("carreras");  
        int gestion = Integer.parseInt(request.getParameter("gestion"));
        String nombreEstudiante = request.getParameter("datosEstudiante");
        
        Connection c = null;
        String aux[] = {};
        int idCarrera = 0;
        String nombreCarrera = "";
        // para la matricula
        List<Matricula> matriculas = new ArrayList<Matricula>();
        // para transaccion
        List<Transaccion> trans = new ArrayList<Transaccion>();
        int idPeriodo = UtilDate.getPeriodo();
        int idTransaccion = 0;
        String fecha = UtilDate.getFechaSqlActual();
        int idFacultad = 0;
        // para el bloqueo necesario aqui
        c = Conector.getConexion();
        TransaccionManager tManager = ManagerFactory.getTransaccionManagerInstance(c);
        MatriculaManager mManager = ManagerFactory.getMatriculaManagerInstance(c);
        VentaMatriculaManager vmManager = ManagerFactory.getVentaMatriculaManagerInstance(c);
        BloqueoManager bloqueoManager = ManagerFactory.getBloqueoManagerInstance(c);
        try{
            
            c.setAutoCommit(false);
            String bloqueoTablas = "LOCK TABLES";
            bloqueoTablas += " TRANSACCION WRITE";
            bloqueoTablas += ", MATRICULA WRITE";
            bloqueoTablas += ", FACULTAD F READ";
            bloqueoTablas += ", DETALLE_ADMINISTRATIVO DA READ";
            bloqueoTablas += ", GESTION G READ";
            bloqueoTablas += ", TIPO_GESTION TG READ";
            bloqueoTablas += ", VENTA_MATRICULA VM READ";
            bloqueoManager.bloquearTablas(bloqueoTablas);
            
            idTransaccion = tManager.getIdTransaccion(idPeriodo);
            // para el reporte
            VentaMatricula vm = vmManager.getVentaMatriculaXfacultad( s_Usuario.getIdUsuario(), UtilDate.getDateTime() );// UtilDate.getDateTime()            
            Gestion g = vm.getGestion();
            Facultad f = g.getFacultad();
            
            java.util.Formatter fmt = new java.util.Formatter();
            fmt.format("%07d",idTransaccion);
            out.println(" <div class='clear:both'>");
            out.println("   <table style='width:100%;float:left;font-weight: bold;'>");
            out.println("	<tr>");
            out.println("           <td style='width:50%;text-align:left'>Entidad Normal </td>");
            out.println("           <td style='width:50%;text-align:right'><u>Periodo:</u> "+idPeriodo+"&nbsp;&nbsp;<u>Nro:</u> "+fmt+"</td>");
            out.println("	</tr>");
            out.println("   </table>");
            out.println(" </div>");
            out.println("<div style='clear:left;text-align:center;'><span><h2 class='decorado'>RECIBO DE CAJA</h2></span></div>");
            
            out.println(" <div style='clear:both'>");
            out.println("   <label class='form_labelAlign'>Periodo :</label>");
            out.println("   <label class='form_labelAlignF'>"+g.getNombre()+"</label><br/>");
            out.println(" </div>");
            out.println(" <div style='clear:both'>");
            out.println("   <label class='form_labelAlign'>Unidad Acad&eacute;mica :</label>");
            out.println("   <label class='form_labelAlignF'>"+f.getNombre()+"</label><br/>");
            out.println(" </div>");
            out.println(" <div style='clear:both'>");
            out.println("   <label class='form_labelAlign'>Estudiante :</label>");
            out.println("   <label class='form_labelAlignF'>"+nombreEstudiante+"</label>");
            out.println(" </div>");
            List<Double> monto = new ArrayList<Double>();// solo para el reporte
            
            for(String ids : carreras){// ids<-- 1_1    idCarrera_idFacultad
                aux = ids.split("_");
                idCarrera = Integer.parseInt(aux[0]);
                idFacultad = Integer.parseInt(aux[1]);
                nombreCarrera = aux[2];
                Transaccion t = new Transaccion();
                t.setIdPeriodo(idPeriodo);
                t.setIdTransaccion(idTransaccion);
                t.setFecha(fecha);
                t.setMonto( UtilTransaccion.redondeo( costo / carreras.length, 2 ) );
                t.setObservacion("VENTA DE MATRICULA");
                t.setIdOperacion(1);
                t.setIdFactura(0);
                t.setIdUsuario(s_Usuario.getIdUsuario());
                t.setIdFacultad(idFacultad);
                t.setIp("0.0.0.0");
                trans.add(t);
                
                
                Matricula m = new Matricula();
                m.setIdGestion(gestion);
                m.setIdMatricula(UtilTransaccion.generarCodigo());
                m.setIdCarrera(idCarrera);
                m.setIdEstudiante(codsis);
                m.setIdPeriodo(idPeriodo);
                m.setIdTransaccion(idTransaccion);
                m.setActivo(true);
                mManager.saveMatricula(m);
                //matriculas.add(m);
                
                idTransaccion++;
                out.println(" <div style='clear:both'>");
                out.println("   <label class='form_labelAlign'>Especialidad :</label>");
                out.println("   <label class='form_labelAlignF'>"+nombreCarrera+"</label>");
                out.println(" </div>");
                
                out.println(" <div style='clear:both'>");
                out.println("   <label class='form_labelAlign'>C&oacute;digo :</label>");
                out.println("   <label class='form_labelAlignF'>"+m.getIdMatricula()+"</label>");
                out.println(" </div>");
                monto.add(t.getMonto());// solo para el reporte
            }
            out.println(" <div style='clear:both'>");
            out.println("   <label class='form_labelAlign'>Cajero :</label>");
            out.println("   <label class='form_labelAlignF'>"+s_Usuario.getNombre()+" "+s_Usuario.getApellido()+"</label>");
            out.println(" </div>");
            out.println(" <div style='clear:both'>");
            out.println("   <label class='form_labelAlign'>Fecha :</label>");
            out.println("   <label class='form_labelAlignF'>"+UtilDate.getFechaActualDetallado()+"</label>");
            out.println(" </div>");
            
            out.println(" <div style='clear:both'>");
            out.println("   <fieldset>");
            out.println("   <legend><u><i>Detalle :</i></u></legend>");
            out.println("   <table style='width:100%' border='0'>");
            out.println("      <tr>");
            out.println("           <td style='width:15%;background:#f0f0f0'><center>Nº</center></td>");
            out.println("           <td style='width:70%;background:#f0f0f0'><center>Concepto</center></td>");
            out.println("           <td style='width:15%;text-align:right;background:#f0f0f0'>Monto</td>");
            out.println("      </tr>");
            
            i = 1;
            for(Double d : monto){
                out.println("      <tr>");
                out.println("           <td>"+i+"</td>");
                out.println("           <td>VENTA DE MATRICULA</td>");
                out.println("           <td style='text-align:right'>"+UtilTransaccion.redondear(d, 2)+"</td>");
                out.println("      </tr>");
                i++;
            }
            
            out.println("      <tr>");
            out.println("           <td colspan='2' style='text-align:right;background:#f0f0f0'>TOTALES :</td>");
            out.println("           <td style='text-align:right;background:#f0f0f0'>"+UtilTransaccion.redondear(costo, 2)+"</td>");
            out.println("      </tr>");
            out.println("      <tr>");
            out.println("           <td colspan='3' class='tamanioFont08em' style='text-align:left'>Obs. : Venta de matr&iacute;cula</td>");
            out.println("      </tr>");
            out.println("   </table>");
            out.println("   </fieldset>");
            out.println(" </div>");
            out.println(" <div class='clear:both'>");
            out.println("   <table style='width:100%;float:left;font-weight: bold;'>");
            out.println("	<tr>");
            out.println("           <td style='width:90%;text-align:right'>Bs </td>");
            out.println("           <td style='width:10%;text-align:left'><u>"+UtilTransaccion.redondear(costo,2)+"</u></td>");
            out.println("	</tr>");
            out.println("   </table>");
            out.println(" </div>");
            out.println(" <div style='clear:both'>");
            out.println("   <label class='form_input_alignF'>SON : "+UtilTransaccion.getFormatoLiteral(costo) +" BOLIVIANOS.</label><br/>");
            out.println(" </div>");
            
            tManager.saveTransacciones(trans);
            //mManager.saveMatriculas(matriculas);
            
            c.commit();
        }catch(DataException e){
            SqlManager.rollBack(c);
            System.out.println(UtilDate.getDateTime()+" Transacciones -> insertMatriculaXfacultad() e: "+e.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Transacciones -> insertMatriculaXfacultad() DataException "+e.getMessage());
            PAGE = ERROR_AJAX;
        }catch(Exception ex){
            SqlManager.rollBack(c);
            System.out.println(UtilDate.getDateTime()+" Transacciones -> insertMatriculaXfacultad() ex: "+ex.getMessage());
            request.setAttribute("msgError", UtilDate.getDateTime()+" Transacciones -> insertMatriculaXfacultad() Exception ex: "+ex.getMessage());
            PAGE = ERROR_AJAX;
        }finally{
            SqlManager.setAutoCommit(c, true);
            bloqueoManager.desBloquearTablas();
            SqlManager.closeConexion(c);
            out.close();
        }
    }    
}
